<template>
  <basicTopContainer v-loading="loading" class="conent">
    <basic-container>
      <div style="height: 50px; margin-right: 10px">
        <el-button
          :disabled="addDisabled"
          style="float: right; margin-left: 10px"
          @click="gotoAddRoom(1)"
          slot="reference"
          type="primary"
          size="small"
          >新增计量点</el-button
        >
      </div>
      <el-container class="container_tree" style="height: 500px">
        <el-aside width="260px" style="border-right: 1px solid #eee">
          <el-input
            style="margin-bottom: 10px"
            placeholder="输入关键字进行过滤"
            v-model="filterText"
          ></el-input>
          <div class="box_btn">
            <span class="box_text">计量点区域</span>
            <el-button
              style="margin-bottom: 5px; float: right"
              @click="openCommunityForm('save')"
              type="primary"
              size="mini"
              >新增区域</el-button
            >
          </div>
          <el-tree
            :data="treeData"
            :props="defaultProps"
            @node-click.self="handleNodeClick"
            node-key="id"
            :filter-node-method="filterNode"
            :default-checked-keys="['1304256051645616130']"
            :default-expanded-keys="['1304256073439219714']"
            ref="tree"
          >
            <div
              @mouseover="treeId = data.id"
              @mouseout="treeId = ''"
              class="custom-tree-node"
              slot-scope="{ node, data }"
            >
              <span class="title_left_span">{{ node.label }}</span>
              <span v-show="treeId == data.id" style="float: right">
                <el-dropdown>
                  <span style="color: #000" class="el-dropdown-link">...</span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item>
                      <div @click.self="openCommunityForm('view', data)">
                        查看区域
                      </div>
                    </el-dropdown-item>
                    <el-dropdown-item :disabled="data.level == 3">
                      <span @click.self="openCommunityForm('add', data)"
                        >创建子区域</span
                      >
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <span @click.self="openCommunityForm('edit', data)"
                        >修改子区域</span
                      >
                    </el-dropdown-item>
                    <el-dropdown-item
                      :disabled="data.child && data.child.length != 0"
                    >
                      <span @click.self="openCommunityForm('remove', data)"
                        >删除子区域</span
                      >
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </span>
            </div>
          </el-tree>
        </el-aside>
        <el-container
          style="overflow: auto; margin-left: 5px; border: 1px solid #eee"
        >
          <div style="width: 100%; padding-left: 10px">
            <quarter-list
              v-if="page === 2"
              :regionData="regionData"
              :name="name"
              :goBackHandle="goBackHandle"
              @refresh="refresh"
            ></quarter-list>
          </div>
        </el-container>
      </el-container>
    </basic-container>
    <!-- <communityForm :communityView.sync="communityView"></communityForm> -->
    <el-dialog
      append-to-body="true"
      :title="communityTitle"
      :visible.sync="communityView"
      width="50%"
      :before-close="dialogBeforeClose"
      @open="communityOpen"
    >
      <el-form
        :rules="rules"
        ref="ruleForm"
        :model="communityForm"
        label-width="100px"
      >
        <!-- 上级位置 -->
        <el-form-item
          style="text-align: left"
          v-if="communityStatus.upShow"
          label="上级位置"
          prop="parentId"
        >
          <el-cascader
            style="width: 80%"
            :disabled="communityStatus.isShow"
            v-model="communityForm.parentId"
            :options="communityTreeData"
            :props="props"
          ></el-cascader>
        </el-form-item>
        <!-- 行政区域 -->
        <el-form-item
          v-if="communityStatus.cityShow"
          label="行政区域"
          prop="province"
        >
          <el-row :gutter="10">
            <el-col :span="7">
              <el-select
                :disabled="communityStatus.isShow"
                placeholder="请选择省"
                v-model="communityForm.province"
                @change="changeProvince"
              >
                <el-option
                  v-for="item in province"
                  :key="item.key"
                  :label="item.title"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="7">
              <el-select
                :disabled="communityStatus.isShow"
                placeholder="请选择市"
                v-model="communityForm.city"
                @change="changeCity"
              >
                <el-option
                  v-for="item in city"
                  :key="item.key"
                  :label="item.title"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="7">
              <el-select
                :disabled="communityStatus.isShow"
                placeholder="请选择区"
                v-model="communityForm.regionId"
              >
                <el-option
                  v-for="item in regionId"
                  :key="item.key"
                  :label="item.title"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <!-- 小区名称 -->
        <el-form-item label="区域名称" prop="name">
          <el-input
            :disabled="communityStatus.addressShow"
            v-model="communityForm.name"
            placeholder
          ></el-input>
        </el-form-item>
        <!-- 详细地址 -->
        <el-form-item
          v-if="communityStatus.detailedShow"
          label="备注"
          prop="address"
        >
          <el-input
            :disabled="communityStatus.addressShow"
            v-model="communityForm.address"
          ></el-input>
        </el-form-item>
        <!-- end -->
      </el-form>
      <div slot="footer">
        <el-button @click="communityView = false">取 消</el-button>
        <el-button type="primary" @click="addTree">确 定</el-button>
      </div>
    </el-dialog>
  </basicTopContainer>
</template>

<script>
// import { getList, getDetail, add, update, remove } from "@/api/meter/room" ;
import { mapGetters, mapState } from "vuex";
import roomSearch from "./components/room/search";
import regionList from "./components/room/regionList";
import quarterList from "./components/room/quarterList";
import { getLazyTree } from "@/api/base/region";
import resultList from "./components/room/resultList";
// import communityForm from "./components/room/communityForm";
import { getRoomList, getEstateList, getList } from "@/api/meter/room";
import {
  getTreeList,
  estateSave,
  estateUpdate,
  estateRemove,
  buildingRemove,
} from "@/api/meter/community";

export default {
  data() {
    return {
      communityTitle: "新增区域",
      addDisabled: true,
      communityStatus: {
        upShow: false, //上级位置
        cityShow: true, // 行政区域
        detailedShow: true, // 详细地址
        isShow: false, // 位置禁用
        addressShow: false, // 小区和地址禁用
        type: "add",
      },
      communityType: "",
      communityForm: {
        name: "", // 小区名称
        parentId: "0", // 上级地区
        province: "", // 省
        city: "", // 市
        regionId: "", // 区
        address: "", // 详细地址
        level: 1, // 层级
      },
      province: [],
      city: [],
      regionId: [],
      rules: {
        parentId: [
          { required: true, message: "请输入上级位置", trigger: "blur" },
        ],
        province: [
          { required: true, message: "请输入行政区域", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入小区名称", trigger: "blur" }],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
      },
      //---------------------------------------------------------------------------
      communityTreeData: [],
      treeId: "",
      communityView: false,
      checkedList: [2],
      treeData: [],
      data: {},
      filterText: "",
      defaultProps: {
        children: "child",
        label: "name",
      },
      name: "",
      activeName: "first",
      loading: false,
      regionData: [],
      searchResult: [],
      roomData: {},
      props: {
        expandTrigger: "hover",
        children: "child",
        label: "name",
        value: "id",
        checkStrictly: true,
      },
      page: 2, // 记录当前所处页面位置 1.最外层小区 2.内部楼层 3.搜索结果页
      fillData: [],
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    ...mapState({
      roomStoreData: (state) => state.room.roomStoreData,
    }),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.room_add, false),
        viewBtn: this.vaildData(this.permission.room_view, false),
        delBtn: this.vaildData(this.permission.room_delete, false),
        editBtn: this.vaildData(this.permission.room_edit, false),
      };
    },
  },
  activated() {
    if (this.roomStoreData.id) {
      this.handleNodeClick(this.roomStoreData);
      getRoomList(this.roomStoreData.id, this.roomStoreData.level).then(
        (res) => {
          this.roomData = res.data.data;
          this.dataFormat(this.roomData);
          // console.log("regionData", this.regionData);
        }
      );
    }
  },
  mounted() {
    getTreeList().then((res) => {
      const data = res.data.data;
      this.treeData = data;
      if (this.roomStoreData.id) {
        this.handleNodeClick(this.roomStoreData);
        getRoomList(this.roomStoreData.id, this.roomStoreData.level).then(
          (res) => {
            this.roomData = res.data.data;
            this.dataFormat(this.roomData);
          }
        );
      }
    });
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    getTreeList() {
      getTreeList().then((res) => {
        const data = res.data.data;
        this.treeData = data;
      });
    },
    // 打开表单
    async openCommunityForm(type, data) {
      console.log(data);
      // this.communityView = true;
      this.communityType = type;
      if (type == "view") {
        this.communityTitle = "查看区域";
        this.empty();
        // 查看--------------------------------------------------
        this.communityStatus.detailedShow = true;
        this.communityStatus.isShow = true;
        this.communityStatus.addressShow = true;
        this.communityStatus.type = type;
        if (data.level == 1) {
          this.communityStatus.upShow = false;
          this.communityStatus.cityShow = true;
        } else {
          this.communityStatus.upShow = true;
          this.communityStatus.cityShow = false;
        }
        this.communityForm = data;
        await this.changeProvince(data.provinceCode);
        this.communityForm.province = data.provinceCode;
        await this.changeCity(data.cityCode);
        this.communityForm.city = data.cityCode;
        this.communityForm.regionId = data.districtCode;
        this.communityView = true;
        // end
      } else if (type == "add") {
        this.communityTitle = "创建子区域";
        this.empty();
        //新增子节点------------------------------------------------------
        this.communityForm.parentId = data.id;
        this.communityStatus.upShow = true;
        this.communityStatus.isShow = false;
        this.communityStatus.cityShow = false;
        this.communityStatus.addressShow = false;
        this.communityStatus.detailedShow = true;
        this.communityStatus.type = type;
        this.communityView = true;
      } else if (type == "edit") {
        this.communityTitle = "修改子区域";
        this.empty();
        //修改节点----------------------------------------
        this.communityStatus.isShow = false;
        this.communityStatus.addressShow = false;
        this.communityStatus.detailedShow = true;
        this.communityStatus.type = type;
        if (data.level == 1) {
          this.communityStatus.upShow = false;
          this.communityStatus.cityShow = true;
        } else {
          this.communityStatus.upShow = true;
          this.communityStatus.cityShow = false;
        }
        this.communityForm = data;
        // this.communityForm.parentId = data.id;
        await this.changeProvince(data.provinceCode);
        this.communityForm.province = data.provinceCode;
        await this.changeCity(data.cityCode);
        this.communityForm.city = data.cityCode;
        this.communityForm.regionId = data.districtCode;
        this.communityView = true;
      } else if (type == "remove") {
        // 删除节点-------------------------------------------------
        this.communityStatus.type = type;
        // this.communityView = true;
        this.removeTree(data);
      } else if (type == "save") {
        this.communityTitle = "新增区域";
        this.empty();
        // 新增根节点---------------------------------------------
        this.communityStatus.upShow = false;
        this.communityStatus.isShow = false;
        this.communityStatus.cityShow = true;
        this.communityStatus.addressShow = false;
        this.communityStatus.detailedShow = true;
        this.communityStatus.type = type;
        this.communityView = true;
      }
      this.$forceUpdate();
    },
    //addTree
    addTree() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          if (
            Object.prototype.toString.call(this.communityForm.parentId) ==
            "[object Array]"
          ) {
            this.communityForm.parentId = this.communityForm.parentId[
              this.communityForm.parentId.length - 1
            ];
          }
          let obj = this.communityForm;
          console.log("this.communityStatus.type", this.communityType);
          console.log(obj);
          if (this.communityType == "add" || this.communityType == "save") {
            estateSave(obj).then((res) => {
              this.$notify({
                message: res.data.msg,
                type: "success",
              });
              this.empty();
              this.getTreeList();
              this.communityView = false;
            });
          } else if (this.communityType == "edit") {
            estateUpdate(obj).then((res) => {
              this.$notify({
                message: res.data.msg,
                type: "success",
              });
              this.empty();
              this.getTreeList();
              this.communityView = false;
            });
          } else {
            this.empty();
            this.communityView = false;
          }
        }
      });
    },
    // open
    communityOpen() {
      getTreeList().then((res) => {
        this.communityTreeData = res.data.data;
      });
      getLazyTree("00").then((res) => {
        this.province = res.data.data;
      });
      // this.empty();
    },
    // 省级地区
    changeProvince(value) {
      this.city = [];
      this.regionId = [];
      this.communityForm.city = "";
      this.communityForm.regionId = "";
      getLazyTree(value).then((res) => {
        this.city = res.data.data;
      });
    },
    //市级地区
    changeCity(value) {
      this.regionId = [];
      this.communityForm.regionId = "";
      getLazyTree(value).then((res) => {
        this.regionId = res.data.data;
      });
    },
    // 删除按钮
    removeTree(val) {
      if (val.child && val.child.length > 0) {
        return this.$notify({
          title: "提示",
          message: "该地区下有下级地区,无法删除",
          type: "warning",
        });
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return buildingRemove(val.id);
          // if (val.level == 1) {
          //   return buildingRemove(val.id);
          // } else if (val.level == 2 || val.level == 3) {
          //   return buildingRemove(val.id);
          // }
        })
        .then((res) => {
          this.$notify({
            message: res.data.msg,
            type: "success",
          });
          this.getTreeList();
        });
    },
    // 清空
    empty() {
      this.communityForm = {
        name: "", // 小区名称
        parentId: "0", // 上级地区
        province: "", // 省
        city: "", // 市
        regionId: "", // 区
        address: "", // 详细地址
        level: 1, // 层级
      };
      // this.communityStatus = {
      //   upShow: false, //上级位置
      //   cityShow: true, // 行政区域
      //   detailedShow: true, // 详细地址
      //   isShow: false, // 位置禁用
      //   addressShow: false, // 小区和地址禁用
      // };
      if (this.$refs["ruleForm"]) {
        this.$refs["ruleForm"].clearValidate();
      }
      // this.province = [];
      this.city = [];
      this.regionId = [];
    },
    //------------------------------------------------------------------
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    refresh() {
      this.handleNodeClick(this.data);
    },
    handleNodeClick(data) {
      if (data.level == 3 || data.child.length == 0) {
        this.addDisabled = false;
      } else {
        this.addDisabled = true;
      }
      this.fillData = data;
      this.$store.commit("SET_ROOM_DATA", data);
      this.data = data;
      this.name = data.name;
      getRoomList(data.id, data.level).then((res) => {
        this.roomData = res.data.data;
        this.dataFormat(this.roomData);
      });
    },
    dataFormat(data) {
      this.page = 2;
      this.regionData = data;
    },
    searchHandle() {},
    clearHandle() {
      // 清空回调
      this.page = 1;
    },

    goBackHandle() {
      this.page = 1;
    },
    gotoAddRoom(val, node, data) {
      console.log("node, data", node, data);
      if (val == 1) {
        this.$router.push({
          path: "/room/decentralized",
          query: {
            type: val,
            data: this.fillData,
          },
        });
      } else {
        this.$router.push({
          path: "/room/decentralized",
          query: {
            type: val,
            data: data,
          },
        });
      }
    },
  },
  components: {
    roomSearch,
    regionList,
    quarterList,
    resultList,
    // communityForm,
  },
};
</script>

<style lang="scss" scoped>
.conent {
  /deep/.basic-top-header {
    display: none;
  }
}

.box_btn {
  // text-align: right;
  font-size: 16px;
  margin-right: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ccc;
  margin-bottom: 5px;

  .box_text {
    font-size: 12px;
  }
}
.room-hover {
  padding: 2px 0;
  margin: 0;
}
.room-hover:hover {
  color: #04a568;
}
.tabs-title {
  display: block;
  line-height: 22px;
  padding-top: 10px;
  transform: translateY(10px);
}
.container_tree {
  /deep/.el-tree-node__label {
    width: 220px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.add_room_btn {
  .el-icon-arrow-down {
    display: none;
  }
}

.custom-tree-node {
  width: 100%;
  padding-right: 10px;
}
.title_left_span {
  display: inline-block;
  width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
